package kim.artemis.rpc.core.protocol.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import kim.artemis.rpc.core.model.ArtemisRpcResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;

/**
 * 客户端处理程序
 * @author Wq.
 */
@Slf4j
public class ArtemisRpcClientHandler extends SimpleChannelInboundHandler<ArtemisRpcResponse> {


    private ArtemisRpcClientInvoker invokerFactory;

    public ArtemisRpcClientHandler(final ArtemisRpcClientInvoker invokerFactory) {
        this.invokerFactory = invokerFactory;
    }

    @SneakyThrows
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 从本地服务副本中删除断开的连接
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        invokerFactory.getServiceRegistry().remove(socketAddress.toString().replace("/", ""));
        log.error(">>>>>>> artemis rpc, client finds an exception: {}", cause.getLocalizedMessage());
        log.error(">>>>>>> artemis rpc, address of the closed connection is: {}", ctx.channel().remoteAddress());
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ArtemisRpcResponse artemisRpcResponse) throws Exception {
        invokerFactory.notifyInvokerFuture(artemisRpcResponse.getArtemisId(), artemisRpcResponse);
    }
}
